﻿namespace RainbowNavBar.View
{
    /// <summary>
    /// Add.xaml 的交互逻辑
    /// </summary>
    public partial class Add : Window
    {
        private readonly static Random random = new Random();

        private int index = 0;

        // 拷贝对象
        public TagData _TagData = null;
        // 临时存储
        public TagData _TempTagData = null;

        public Add(bool T, TagData td = null)
        {
            InitializeComponent();
            this.Loaded += (s, e) =>
            {
                if (T)
                {
                    this.Title = "添加标签";
                    this.TagColor.Text = GenerateRandomColorHex();
                    this.url.IsChecked = true;
                    this.BtnTag.Content = "添加标签";

                    this.TagIndex.Text = (ApplicationConfig.TagListData.Count + 1).ToString();
                }
                else
                {
                    // 拷贝对象：用于之后的判断
                    _TagData = new(td);
                    // 复制对象：用于修改
                    _TempTagData = td;

                    this.Title = "更新标签";
                    if (td.TagType == FunType.URL)
                    {
                        this.url.IsChecked = true;
                    }
                    if (td.TagType == FunType.APPLICATION)
                    {
                        this.apply.IsChecked = true;
                    }
                    this.TagIndex.Text = td.TagIndex.ToString();
                    this.TagColor.Text = GlobalFunction.ToHexString(td.TagColor);
                    this.IsTagEnable.IsChecked = td.TagEnable;
                    this.BtnTag.Content = "更新标签";
                    this.TagName.Text = td.TagName;
                    this.TagAddress.Text = td.TagAddress;
                    this.TagDescription.Text = td.TagDescription;
                }
            };
        }

        #region 标签操作

        /// <summary>
        /// 添加标签
        /// </summary>
        /// <param name="index">类型索引</param>
        /// <param name="tagName"></param>
        /// <param name="tagDescription"></param>
        /// <param name="tagAddress"></param>
        /// <param name="tagColor"></param>
        private void TagAdd(int index, string tagName, bool isEnable, string tagDescription, string tagAddress, string tagColor, int tagIndex)
        {
            // 创建标签
            Label _label = new()
            {
                Width = 10,
                Height = 30,
                Content = tagName,
                Background = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(tagColor)),
            };

            // 创建对象
            TagData _td = new()
            {
                TagIndex = tagIndex,
                TagLabel = _label,
                TagType = (FunType)index,
                TagEnable = isEnable,
                TagName = tagName,
                TagDescription = tagDescription,
                TagAddress = tagAddress,
                TagColor = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(tagColor),
                TagColor_s = (Brush)new BrushConverter().ConvertFromString(tagColor),
                //TagIcon = GetTypeIcon((FunType)Convert.ToInt32(record["TagType"])),                     
                TagIcon = ApplicationConfig.GetApplicationIconAsync(tagAddress, (FunType)index),
            };

            // 通知列表更新数据
            TagManagement.SyncDataLocal(_td);

            // 添加对象到全局列表中
            ApplicationConfig.TagAdd(_td,
            new Dictionary<string, string>
                {
                    {"TagIndex",tagIndex.ToString() },
                    {"TagType",index.ToString() },
                    {"TagName",tagName },
                    {"TagEnable",isEnable.ToString() },
                    {"TagDescription",tagDescription },
                    {"TagAddress",tagAddress },
                    {"TagColor",tagColor },
            });

            // 弹出信息框
            MessBox("添加成功: " + tagName, EMColor.Success);

            // 标签添加完成后销毁窗口
            this.Close();
        }

        /// <summary>
        /// 更新标签
        /// </summary>
        /// <param name="tagName"></param>
        /// <param name="td"></param>
        private void TagUpdate(string tagName, TagData td)
        {
            // 封装更新后的字典
            var updatedRecord = new System.Collections.Generic.Dictionary<string, string>
            {
                { "TagName", td.TagName },
                { "TagIndex", (td.TagIndex).ToString() },
                { "TagType", ((int)td.TagType).ToString() },
                { "TagEnable",td.TagEnable.ToString() },
                { "TagDescription", td.TagDescription },
                { "TagAddress", td.TagAddress },
                { "TagColor",  "#" + this.TagColor.Text},
                //{ "TagColor", "#ff5722" },
            };

            // 通知列表更新数据
            TagManagement.TagListDataUpdate(td);

            // 更新对象到全局列表中
            ApplicationConfig.TagUpdated(td, tagName, updatedRecord);

            // 重新加载窗体标签
            MainWindow.ReloadData();

            // 弹出信息框
            MessBox("修改成功: " + tagName, EMColor.Success);

            // 标签添加完成后销毁窗口
            this.Close();

        }

        /// <summary>
        /// 事件：添加/更新标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            // 检测索引值是否符合要求
            if (!this.IsNumberIndex(this.TagIndex.Text))
            {
                MessBox("您输入的索引值有误，请重新输入...", EMColor.Error);
                return;
            }

            // 检测颜色值是否符合要求
            if (!this.IsColor(this.TagColor.Text))
            {
                MessBox("您输入的颜色值有误，请重新输入...", EMColor.Error);
                return;
            }

            if (this.Title == "更新标签")
            {
                if (IsUpdateTagName(_TagData.TagName))
                {
                    MessBox("名称标识已经存在，请重新填写！", EMColor.Warning);
                    return;
                }
                _TempTagData.IsModify = true;
                //_TempTagData.TagIndex = Convert.ToInt32(this.TagIndex.Text);
                _TempTagData.TagType = (FunType)index;
                _TempTagData.TagEnable = (bool)this.IsTagEnable.IsChecked;
                _TempTagData.TagName = this.TagName.Text;
                _TempTagData.TagDescription = this.TagDescription.Text;
                _TempTagData.TagAddress = this.TagAddress.Text;
                _TempTagData.TagColor = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#" + this.TagColor.Text);
                _TempTagData.TagColor_s = (Brush)new BrushConverter().ConvertFromString("#" + this.TagColor.Text);

                TagData tagData = new(_TempTagData)
                {
                    IsModify = true,
                    TagName = this.TagName.Text,
                    TagIcon = _TempTagData.TagIcon,
                    TagEnable = (bool)this.IsTagEnable.IsChecked,
                    TagType = (FunType)index,
                    TagIndex = Convert.ToInt32(this.TagIndex.Text),
                    TagLabel = _TempTagData.TagLabel,
                    TagAddress = this.TagAddress.Text,
                    TagDescription = this.TagDescription.Text,
                    TagColor = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#" + this.TagColor.Text),
                    TagColor_s = (Brush)new BrushConverter().ConvertFromString("#" + this.TagColor.Text),
                };

                if (!_TagData.Equals(tagData))
                {
                    // 检测索引值是否被使用
                    var _indexNumber = ApplicationConfig.IsTagIndexExists(Convert.ToInt32(this.TagIndex.Text));

                    if (_indexNumber.Item1)
                    {
                        // 交换排序索引值
                        _indexNumber.Item2.TagIndex = _TagData.TagIndex; // 原始数据
                        _TempTagData.TagIndex = Convert.ToInt32(this.TagIndex.Text); // 新数据

                        // MessBox("该序号已被使用，请重新设置索引值！", EMColor.Error);
                    }
                    else
                    {
                        _TempTagData.TagIndex = Convert.ToInt32(this.TagIndex.Text); // 新数据
                    }

                    // 设置查询到的对象
                    ApplicationConfig.TagListData.Sort((t1, t2) => t1.TagIndex.CompareTo(t2.TagIndex));

                    TagUpdate(_TagData.TagName, _TempTagData);
                }
                else
                {
                    MessBox("无法更新：您没有修改数据！", EMColor.Warning);
                }
            }

            if (this.Title == "添加标签")
            {
                if (CheckTagName())
                {
                    // 不存在
                    if (this.TagName.Text == string.Empty)
                    {
                        //this.Hint.Foreground = new SolidColorBrush(Colors.DarkRed);
                        //this.Hint.Text = "名称不能为空！";
                        MessBox("名称不能为空，请输入标签名称！", EMColor.Warning);
                        return;
                    }
                    if (this.TagAddress.Text == string.Empty)
                    {
                        //this.Hint.Foreground = new SolidColorBrush(Colors.DarkRed);
                        //this.Hint.Text = "地址不能为空！";
                        MessBox("地址不能为空，请输入映射地址！", EMColor.Warning);
                        return;
                    }
                    if (this.TagColor.Text == string.Empty)
                    {
                        //this.Hint.Foreground = new SolidColorBrush(Colors.DarkRed);
                        //this.Hint.Text = "背景色不能为空，请输入十六进制颜色值！";
                        MessBox("背景色不能为空，请输入十六进制颜色值！", EMColor.Warning);
                        return;
                    }

                    if (this.index == 0 && !IsUrl(this.TagAddress.Text))
                    {
                        //this.Hint.Foreground = new SolidColorBrush(Colors.DarkRed);
                        //this.Hint.Text = "您输入的网址错误，请重新输入！";
                        MessBox("您输入的网址错误，请重新输入！", EMColor.Error);
                        this.TagAddress.Text = string.Empty;
                        return;
                    }

                    if ((this.index == 1 || this.index == 2) && !PathExists(this.TagAddress.Text))
                    {
                        //this.Hint.Foreground = new SolidColorBrush(Colors.DarkRed);
                        //this.Hint.Text = "您输入的应用地址错误，请重新输入！";
                        MessBox("您输入的应用地址错误，请重新输入！", EMColor.Warning);
                        this.TagAddress.Text = string.Empty;
                        return;
                    }

                    this.TagAdd(this.index, this.TagName.Text, (bool)this.IsTagEnable.IsChecked, this.TagDescription.Text, this.TagAddress.Text, "#" + this.TagColor.Text, Convert.ToInt32(this.TagIndex.Text));
                }
                else
                {
                    // 存在
                    //this.Hint.Foreground = new SolidColorBrush(Colors.DarkRed);
                    //this.Hint.Text = "名称或地址已经存在！";
                    MessBox("名称或地址已经存在，请重新填写！", EMColor.Warning);
                }
            }
        }

        #endregion

        #region 数据校验

        /// <summary>
        /// 判断索引值是否合法
        /// </summary>
        /// <param name="color"></param>
        /// <returns></returns>
        private bool IsNumberIndex(string color)
        {
            // 正则表达式：可以带或不带#，6个十六进制字符
            var pattern = @"^[0-9]+$";
            return Regex.IsMatch(color, pattern);
        }

        /// <summary>
        /// 判断十六进制值是否合法（规则：#FFAADD 或 FFAADD）
        /// </summary>
        /// <param name="color">十六进制值 (示例：#FFAADD 或 FFAADD)</param>
        /// <returns>如果符合规则返回 true，否则返回 false</returns>
        private bool IsColor(string color)
        {
            // 正则表达式：可以带或不带#，6个十六进制字符
            var pattern = @"^#?([0-9A-Fa-f]{6})$";
            return Regex.IsMatch(color, pattern);
        }

        /// <summary>
        /// 判断路径是否存在（文件或文件夹）
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns>如果路径存在返回 true，否则返回 false</returns>
        private bool PathExists(string path)
        {
            return System.IO.File.Exists(path) || System.IO.Directory.Exists(path);
        }

        /// <summary>
        /// 判断字符串是否是有效网址
        /// </summary>
        /// <param name="url">输入字符串</param>
        /// <returns>如果是有效网址返回 true，否则返回 false</returns>
        private bool IsUrl(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
                return false;

            // 正则表达式匹配网址
            string pattern = @"^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$";
            return System.Text.RegularExpressions.Regex.IsMatch(url, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 判断字符串是否是有效网址（更加严格）
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private bool IsUrlStrict(string url)
        {
            return Uri.TryCreate(url, UriKind.Absolute, out Uri result)
           && (result.Scheme == Uri.UriSchemeHttp || result.Scheme == Uri.UriSchemeHttps || result.Scheme == Uri.UriSchemeFtp);
        }

        /// <summary>
        /// 数据校验，输入的名称或地址是否已经存在
        /// </summary>
        /// <returns></returns>
        private bool CheckTagName()
        {
            // 如果 TagName 或 TagAddress 为空，直接返回 true 表示通过校验
            if (string.IsNullOrWhiteSpace(this.TagName.Text) || string.IsNullOrWhiteSpace(this.TagAddress.Text))
            {
                return true;
            }
            // 判断是否存在与 TagName和TagAddress 匹配的项
            return !ApplicationConfig.TagListData.Any(tag => tag.TagName != null && (tag.TagName.IndexOf(this.TagName.Text, StringComparison.OrdinalIgnoreCase) >= 0 || tag.TagAddress.IndexOf(this.TagAddress.Text, StringComparison.OrdinalIgnoreCase) >= 0));
        }

        /// <summary>
        /// 更新数据校验，输入的名称或地址是否已经存在
        /// </summary>
        /// <returns></returns>
        private bool IsUpdateTagName(string _thisName)
        {
            // 如果 TagName 或 TagAddress 为空，直接返回 true 表示通过校验
            if (string.IsNullOrWhiteSpace(this.TagName.Text) || string.IsNullOrWhiteSpace(this.TagAddress.Text))
            {
                return true;
            }

            //var results = ApplicationConfig.TagListData.Where(tag => (tag.TagName != null && tag.TagName.Equals(this.TagName.Text, StringComparison.OrdinalIgnoreCase))).ToList();

            return ApplicationConfig.TagListData.Any(tag => tag.TagName != null && tag.TagName.Equals(this.TagName.Text, StringComparison.OrdinalIgnoreCase) && tag.TagName != _thisName);
        }

        #endregion

        #region 色彩颜色

        /// <summary>
        /// 生成随机颜色的16进制表示（不包含#）
        /// </summary>
        /// <returns></returns>
        public static string GenerateRandomColorHex()
        {
            byte r = (byte)random.Next(0, 256); // Random.Next(0, 256) 实际上会返回0到255之间的整数
            byte g = (byte)random.Next(0, 256);
            byte b = (byte)random.Next(0, 256);

            // 将RGB值转换为16进制字符串
            return r.ToString("X2") + g.ToString("X2") + b.ToString("X2");
        }

        /// <summary>
        /// 将Color对象转换为16进制字符串（不包含#）
        /// </summary>
        /// <param name="color"></param>
        /// <returns></returns>
        public static string ColorToHex(Color color)
        {
            return color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
        }

        /// <summary>
        /// 根据RGB值创建Color对象，并转换为16进制字符串（不包含#）
        /// </summary>
        /// <param name="r"></param>
        /// <param name="g"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static string RgbToHex(byte r, byte g, byte b)
        {
            Color color = Color.FromRgb(r, g, b);
            return ColorToHex(color);
        }

        #endregion

        #region 标签地址

        /// <summary>
        /// URL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void url_Checked(object sender, RoutedEventArgs e)
        {
            this.TagAddress.Tag = "https://";
            this.index = 0;
        }

        /// <summary>
        /// 应用地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void apply_Checked(object sender, RoutedEventArgs e)
        {
            this.TagAddress.Tag = "应用地址";
            this.TagAddress.Padding = new Thickness(5, 0, 50, 0);
            this.SelectAddress.Visibility = Visibility.Visible;

            this.index = 1;
        }

        /// <summary>
        /// 取消选择：应用地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void apply_Unchecked(object sender, RoutedEventArgs e)
        {
            this.TagAddress.Padding = new Thickness(5, 0, 5, 0);
            this.SelectAddress.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 文件地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void file_Checked(object sender, RoutedEventArgs e)
        {
            this.TagAddress.Tag = "文件地址";
            this.TagAddress.Padding = new Thickness(5, 0, 50, 0);
            this.SelectAddress.Visibility = Visibility.Visible;

            this.index = 2;
        }

        /// <summary>
        /// 取消选择：文件地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void file_Unchecked(object sender, RoutedEventArgs e)
        {
            this.TagAddress.Padding = new Thickness(5, 0, 5, 0);
            this.SelectAddress.Visibility = Visibility.Collapsed;
        }

        #endregion

        /// <summary>
        /// 取消添加，销毁窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelTag_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectAddress_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new()
            {
                Filter = "All Files (*.*)|*.*", // 你可以根据需要设置文件筛选器
                Title = "选择文件"
            };

            if (ofd.ShowDialog() == true)
            {
                // Debug.WriteLine(ofd.FileName);
                this.TagAddress.Text = ofd.FileName;
            }
        }

    }
}
